package com.aizhixin.lab.project.course.service;

import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.project.course.domain.GuideDomain;
import com.aizhixin.lab.project.course.entity.Guide;
import com.aizhixin.lab.project.course.repository.GuideRepository;
import com.aizhixin.lab.project.course.vo.GuideVo;
import com.aizhixin.lab.task.domain.ReleaseTaskDomain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class GuideService {
    @Autowired
    private GuideRepository guideRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;

    public String save(GuideDomain domain) {
        Guide guide;
        if (StringUtils.isEmpty(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            guide = new Guide();
        } else {
            guide = guideRepository.findOne(domain.getId());
        }
        BeanUtils.copyProperties(domain, guide);
        guideRepository.save(guide);
        return guide.getId();
    }

    RowMapper<GuideVo> guideVoRowMapper = new RowMapper<GuideVo>() {

        @Override
        public GuideVo mapRow(ResultSet rs, int rowNum) throws SQLException {

            GuideVo domain = new GuideVo();
            domain.setId(rs.getString("id"));
            domain.setFileId(rs.getString("file_id"));
            domain.setFileName(rs.getString("file_name"));
            domain.setGuide(rs.getString("guide"));
            domain.setWorkOrderId(rs.getString("work_order_id"));
            domain.setWorkOrderName(rs.getString("w_name"));
            domain.setFileUrl(rs.getString("file_url"));
            return domain;
        }
    };

    public List<GuideVo> findGuideVoList(String id) {
        String sql = "SELECT cg.id,cg.guide,cg.file_id,cm.file_name,cg.work_order_id,ct.w_name,cm.file_url FROM c_guide cg LEFT JOIN c_module_task_file cm ON cg.file_id=cm.id LEFT JOIN c_task_work_order ct ON cg.file_id=ct.id WHERE cg.teacher_task_id='" + id + "' ORDER BY cg.created_date ASC";//
        return pageJdbcUtil.getInfo(sql,guideVoRowMapper);
    }
    public void delete(String id) {
        guideRepository.delete(id);
    }

}
